<template>
    <div class="dooya-container" style="min-width: 1100px;overflow:scroll;">


        <Row   style="background-color: #fff;height: 50px;"  >
                <Col span="12" offset="0"  style="height: 50px;display:flex;flex-wrap:nowrap;flex-direction:row;justify-content:start;align-items:center;padding:10px;">
                    <h3>菜单管理</h3>
                </Col>

                <Col span="12" offset="0"  style="height: 50px; display:flex;flex-wrap:nowrap;flex-direction:row;justify-content:end;align-items:center;">
                         <Button  @click="insert()"  small icon="ios-add-circle" type="primary" style="height: 30px;margin-right: 10px;">新增</Button>
                </Col>
        </Row>
        <hr>
       
        <Row>
            <Col span="24" offset="0">
                <Card shadow :bordered="false" >

       
                    <Table :columns="columns" :data="tableData" border collapsible  style="margin:20px 5px;"
                     ></Table>
                    <!-- Modal - 角色 -->
                    <Modal v-model="modalShowRole" :mask-closable="false" :closable="false" footer-hide
                        :title="modalDataRoleType === 'edit' ? '编辑菜单' : '新增菜单'" @on-ok="handleSubmitRole">
                        <Form ref="formModalDataRole" :model="modalDataRole" :rules="formModalRule" :label-width="100"
                            @submit.native.prevent>
                            <FormItem label="上级菜单：" prop="pid">
                                    <Select v-model.trim="modalDataRole.pid" style="width:200px">


                                        <Option v-for="item in menuSelect" :value="item.id" :key="item.id">

                                            <template  v-if="item.level == 1">
                                            </template>
                                            <template v-else-if ="item.level == 2">
                                                <i class="ml10"></i>
                                            </template>
                                            <template v-else-if ="item.level == 3">
                                                <i class="ml10"></i>
                                                <i class="ml10"></i>
                                            </template>
                                            <template v-else>
                                                <i class="ml10"></i>
                                                <i class="ml10"></i>
                                                <i class="ml10"></i>
                                            </template>

                                            <i  v-if="item.id != 0" class="iconDivider"></i>
                                            {{ item.title }}

                                        </Option>

                                    </Select>
                            </FormItem>
                            <FormItem label="菜单名称：" prop="title">
                                <Input type="text" v-model.trim="modalDataRole.title"></Input>
                            </FormItem>

                            <!-- 对应数据库里面的path字段 -->
                            <FormItem label="companent" prop="path">
                                <Input type="text" v-model.trim="modalDataRole.path"></Input>
                            </FormItem>

                            <!-- 对应数据库里面的name字段 -->
                            <FormItem label="权限名称" prop="name">
                                <Input type="text" v-model.trim="modalDataRole.name"></Input>
                            </FormItem>

                            <FormItem label="排序" prop="sort">
                                <Input type="text" v-model.trim="modalDataRole.sort"     placeholder="值越大菜单越靠前，值是自然数"></Input>
                            </FormItem>

                            <FormItem label="菜单层级" prop="level">
                                <Select v-model.trim="modalDataRole.level" style="width:100px" type="number">
                                    <Option v-for="item in menulevel" :value="item.id" :key="item.id">{{ item.id }}</Option>
                                </Select>
                            </FormItem>
                
                            <FormItem label="是否公共方法" prop="is_common_fun">

                                <template>
                                    <i-switch v-model="modalDataRole.is_common_fun" >
                                        <span slot="open">是</span>
                                        <span slot="close">否</span>
                                    </i-switch>
                                </template>

                            </FormItem>

                            <FormItem label="是否为菜单" prop="menu_type">
                                    <template>
                                        <i-switch v-model="modalDataRole.menu_type" >
                                            <span slot="open">是</span>
                                            <span slot="close">否</span>
                                        </i-switch>
                                    </template>
                            </FormItem>

                            <FormItem label="图标" prop="icon">
                                <Input type="text" v-model.trim="modalDataRole.icon"></Input>
                            </FormItem>

                            <FormItem>
                                <Button type="primary" @click="handleSubmitRole('formModalDataRole')"
                                    :loading="buttonLoading">确定</Button>
                                <Button @click="handleReset('formModalDataRole')" style="margin-left: 8px">Reset</Button>
                                <Button @click="modalShowRole = false" style="margin-left: 8px">取消</Button>
                                
                            </FormItem>
                        </Form>
                    </Modal>

                </Card>
            </Col>
        </Row>

       
    </div>

</template>
<script>
import {
    delMenu, //删除菜单
    addMenu, //添加菜单
    editMenu, //修改菜单
    getUserList, // 获取用户列表
    getMenuList, // 获取菜单列表
    setSort // 排序
} from "@/api/data";

import {
    computedMenuData, // 菜单数据转换成iview树形数据结构(2层)
    arraySort, // 对象数组根据key排序
    resultCallback, // 根据请求的status执行回调函数
    getValueByKey // 根据对象数组某个key的value，查询另一个key的value
} from "@/libs/dataHanding";

export default {
    data() {
        return {
            columns: [
                {
                    title: "序号",
                    key: "id",
                    width: 50,
                    // ellipsis: true,
                    align: "center",
                    render: (h, params) => {
                        let _this = this;
                        if (
                            params.row.children &&
                            params.row.children.length > 0
                        ) {
                            return h(
                                "div",
                                {
                                    class: {}
                                },
                                [
                                    h(
                                        "div",
                                        {
                                            class: {
                                                "ivu-table-cell-tree": true,
                                                "ivu-table-cell-tree-empty":
                                                    params.row.children &&
                                                    params.row.children.length >
                                                        0
                                                        ? false
                                                        : true
                                            },
                                            style: {
                                                "font-size": "16px",
                                                "margin-top": "15px"
                                            }
                                        },
                                        [
                                            h("Icon", {
                                                style: {
                                                    cursor: "pointer"
                                                },
                                                props: {
                                                    type: !params.row.expand
                                                        ? "md-add"
                                                        : "md-remove"
                                                },
                                                on: {
                                                    click: () => {
                                                        this.toogleRow(
                                                            params.row,
                                                            params.index
                                                        );
                                                    }
                                                }
                                            })
                                        ]
                                    ),

                                    h(
                                        "Poptip",
                                        {
                                            props: {
                                                trigger: "hover",
                                                placement: "top",
                                                transfer: true
                                                //content: params.row.name
                                            }
                                        },
                                        [
                                            h(
                                                "div",
                                                {
                                                    style: {
                                                        display: "inline-block",
                                                        padding: "5px 0"
                                                    }
                                                }
                                                //params.row.name
                                            )
                                        ]
                                    )
                                ]
                            );
                        } else {
                            return "";
                        }
                    }
                },
                {
                    title: "菜单名称",
                    key: "title",
                    minWidth: 150,
                    render: (h, params) => {
                        // 生成层级符号
                        let icon_t = h("i", {
                            style: {
                                marginRight: "15px"
                            },
                            class: "iconDivider"
                        });
                        let txt = h("span", params.row.title);

                        let arr = [];
                        for (let i = 1; i <= params.row.level; i++) {
                            arr.push(icon_t);
                        }
                        arr.push(txt);
                        return h("div", arr);
                    }
                },
                {
                    title: "图标",
                    key: "icon",
                    width: 100
                },
                {
                    title: "compant",
                    key: "path",
                    minWidth: 150
                },
                {
                    title: "排序",
                    key: "paixu",
                    // fixed: "right",
                    width: 90,
                    align: "center",
                    render: (h, params) => {
                        return h("Input", {
                            props: {
                                value: params.row.sort,
                                size: "small",
                                placeholder: "请输入选择的数量",
                                type: "number"
                            },
                            on: {
                                input: val => {
                                    if (val < 0) {
                                        this.$Message.error("请输入自然数！");
                                    }
                                    //传排序行的id,和排序后的值
                                    this.sorted(params.row.id, val);
                                }
                            }
                        });
                    }
                },
                {
                    title: "状态",
                    key: "status",
                    width: 80,
                    align: "center",
                    render: (h, params) => {
                        let texts = "";
                        if (params.row.status == "1") {
                            texts = "启用";
                        } else {
                            texts = "禁用";
                        }
                        return h(
                            "div",
                            {
                                props: {
                                    type: "text",
                                    size: "small"
                                },
                                style: {
                                    color:
                                        params.row.status == "1"
                                            ? "#1E90FF"
                                            : "#DC143C"
                                }
                            },
                            texts
                        );
                    }
                },

                {
                    title: "是否为菜单",
                    key: "menu_type",
                    align: "center",
                    width: 80,
                    render: (h, params) => {
                        let texts = "";
                        if (params.row.menu_type == true) {
                            texts = "是";
                        } else {
                            texts = "否";
                        }
                        return h(
                            "div",
                            {
                                props: {
                                    type: "text",
                                    size: "small"
                                },
                                style: {
                                    color:
                                        params.row.menu_type == true
                                            ? "#1E90FF"
                                            : "#DC143C"
                                }
                            },
                            texts
                        );
                    }
                },

                {
                    title: "是否公共方法",
                    key: "is_common_fun",
                    align: "center",
                    width: 80,
                    render: (h, params) => {
                        let texts = "";
                        if (params.row.is_common_fun == true) {
                            texts = "是";
                        } else {
                            texts = "否";
                        }
                        return h(
                            "div",
                            {
                                props: {
                                    type: "text",
                                    size: "small"
                                },
                                style: {
                                    color:
                                        params.row.is_common_fun == true
                                            ? "#1E90FF"
                                            : "#DC143C"
                                }
                            },
                            texts
                        );
                    }
                },

                {
                    title: "操作",
                    key: "action",
                    // fixed: "right",
                    minWidth: 50,
                    align: "center",
                    render: (h, params) => {
                        return h("div", [
                            h(
                                "Button",
                                {
                                    props: {
                                        type: "text",
                                        size: "small"
                                    },
                                    style: {
                                        color: "#1E90FF",
                                        marginRight: "5px"
                                    },
                                    on: {
                                        click: () => {
                                            this.edit(params.row);
                                        }
                                    }
                                },
                                "编辑"
                            ),

                            h(
                                "Tooltip",
                                {
                                    props: {
                                        trigger: "hover",
                                        content: "删除",
                                        placement: "top",
                                        transfer: true
                                    }
                                },
                                [
                                    h("Button", {
                                        props: {
                                            type: "error",
                                            size: "small",
                                            icon: "md-close",
                                            disabled:
                                                params.row.name ===
                                                "super_admin"
                                        },
                                        on: {
                                            click: () => {
                                                this.del(params.row);
                                            }
                                        }
                                    })
                                ]
                            )
                        ]);
                    }
                }
            ],
            tableData: [], // 处理后的当页数据

            /* loading */
            tableLoading: false, // table
            buttonLoading: false, // button
            /* modal弹框 */
            modalShowRole: false, // 是否显示 - role
          
            modalDataRoleDefault: {
                title: "",
                name: "",
                path: "",
                sort: "1",
                level: "",
                is_common_fun: false,
                menu_type: false,
                icon: ""
            },
            modalDataRole: {
                title: "",
                name: "",
                path: "",
                sort: "1",
                level: "",
                is_common_fun: false,
                menu_type: false,
                icon: ""
            },
            //下拉菜单数据
            menuSelect: [],

            // 数据 - role
            modalDataMenu: {
                menus: []
            }, // 数据 - menu
            modalDataRoleOrg: {}, // 数据 - role行内原始
            menuSelectList: [], // 已选择的menu - 接口数据
            menuSelectedId: [], // tree提交的menu - id
            formModalRule: {
                // 对应数据库里面的title
                title: [
                    {
                        required: true,
                        message: "请输入菜单名称",
                        trigger: "change"
                    },
                    {
                        type: "string",
                        max: 30,
                        message: "菜单名称过长",
                        trigger: "change"
                    }
                ],
                //对应数据库里面的name
                name: [
                    {
                        required: true,
                        message: "请输入权限名称",
                        trigger: "change"
                    },
                    {
                        type: "string",
                        max: 30,
                        message: "权限名称过长",
                        trigger: "change"
                    }
                ],
                //对应数据库里面的path
                path: [
                    {
                        required: true,
                        message: "请输入路径名称",
                        trigger: "change"
                    },
                    {
                        type: "string",
                        max: 40,
                        message: "权限名称过长",
                        trigger: "change"
                    }
                ],
                //对应数据库里面的level
                level: [
                    {
                        required: true,
                        message: "请选择层级",
                        trigger: "change",
                        type: "number",
                        min: 1
                    }
                ]
            }, // form规则

            modalDataRoleType: "", // 类型：insert/edit
            menulevel: [
                { id: 1, key: "xx1" },
                { id: 2, key: "xx2" },
                { id: 3, key: "xx3" },
                { id: 4, key: "xx4" }
            ]
        };
    },
    async created() {
        this.getData();
    },
    methods: {
        // 获取列表数据
        async getData() {
            this.tableData =
                (await getMenuList({ menu_type: 1 })).data.data || [];

            console.log("tableData:", this.tableData);

            let tmp = (await getMenuList({ menu_type: 2 })).data.data || [];
            console.log("tmp:", tmp);
            tmp.unshift({ id: 0, pid: 0, title: "无", level: 1 });
            this.menuSelect = tmp;

            this.buttonLoading = false;
            this.tableLoading = false;
        },
        toogleRow(row, index) {
            if (row.expand) {
                this.tableData.splice(index + 1, row.children.length);
            } else {
                this.tableData.splice(index + 1, 0, ...row.children);
            }
            this.tableData[index].expand = !this.tableData[index].expand;
        },

        // 点击按钮 - 新增菜单
        async insert() {
            this.modalDataRoleType = "insert";

            this.modalShowRole = true;

            console.log("insert");
        },

        // 点击按钮 - 编辑
        async edit(row) {
            console.log("row:", row);
            this.modalDataRoleType = "edit";
            // this.roleId = row.id;
            // this.modalDataRoleOrg = row;
            this.modalDataRole = JSON.parse(JSON.stringify(row));
            this.modalShowRole = true;

            console.log("edit");
        },
        // 提交表单 - 角色
        handleSubmitRole() {
            // console.log(this.modalDataRole);
            this.$refs.formModalDataRole.validate(async valid => {
                if (valid) {
                    this.buttonLoading = true;
                    switch (this.modalDataRoleType) {
                        case "insert":
                            let insert_data = {};

                            insert_data.pid = this.modalDataRole.pid;
                            insert_data.title = this.modalDataRole.title;
                            insert_data.name = this.modalDataRole.name;
                            insert_data.path = this.modalDataRole.path;
                            insert_data.sort = this.modalDataRole.sort;
                            insert_data.level = this.modalDataRole.level;
                            insert_data.is_common_fun = this.modalDataRole.is_common_fun;
                            insert_data.menu_type = this.modalDataRole.menu_type;
                            insert_data.icon = this.modalDataRole.icon;

                            console.log("insert_data:", insert_data);

                            //请求后端数据
                            let res_add = await addMenu(insert_data);

                            console.log("res_add:", res_add);
                            if (res_add.data.code != 0) {
                                //axios.js 已经截取了错误信息，这里不需要提示了。
                            } else {
                                resultCallback(200, "添加成功！", () => {
                                    this.getData();
                                    this.modalShowRole = false;
                                });
                            }
                            this.buttonLoading = false;
                            break;

                        case "edit":
                            let data = this.modalDataRole;
                            // data.is_common_fun= data.is_common_fun
                            // data.menu_type = data.menu_type
                            delete data.children;
                            console.log("editdata:", data);

                            //请求后端数据
                            let res = await editMenu(data);

                            if (res.data.code != 0) {
                                //axios.js 已经截取了错误信息，这里不需要提示了。
                            } else {
                                resultCallback(200, "修改成功！", () => {
                                    this.getData();
                                    this.modalShowRole = false;
                                });
                            }
                            this.buttonLoading = false;
                            break;
                    }
                }
            });
        },

        // 点击按钮 - 删除
        del(row) {
            this.$Modal.confirm({
                title: "删除后不能恢复，确定删除？",
                onOk: async () => {
                    //请求后端数据
                    let data = {};
                    data.id = row.id;
                    let res = await delMenu(data);

                    if (res.data.code != 0) {
                        //axios.js 已经截取了错误信息，这里不需要提示了。
                    } else {
                        resultCallback(200, "删除成功！", () => {
                            this.getData();
                        });
                    }
                },
                closable: true
            });
        },
        sorted(id, val) {
            //参数设置
            val = val.trim();
            let data = {
                id: id,
                val: val
            };

            return new Promise((resolve, reject) => {
                setSort(data)
                    .then(res => {
                        //返回提示：
                        const msg = res.data.msg;
                        const code = res.data.code;
                        console.log(res);
                        resolve(res);

                        if (code == 0) {
                            resultCallback(200, msg, () => {
                                this.getData();
                            });
                        } else {
                            resultCallback(201, msg);
                        }
                    })
                    .catch(err => {
                        reject(err);
                    });
            });
        },
        handleReset(name) {
            this.$refs[name].resetFields();
        }
    }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.dooya-container /deep/ {
    .ivu-table-body {
        overflow: hidden;
    }
    .ivu-table {
        th {
            text-align: center;
            height: 60px;
            background-color: #f6f6f8;
            color: #1f2d3d;
        }
    }
}
/deep/.ivu-table-cell-tree {
    .ivu-icon {
        font-size: 14px;
    }
}
</style>
